Lab - 4: Fundamental Dart programming language
By Drashya Patel on 2024-12-12T11:58-05:00
Tags: No Tags
Q1: Topic Overview
Definition of Collections
Collections in Dart programming refer to data structures that hold multiple values or items in a single variable. They are crucial when managing a group of data sets or items efficiently.
-
Lists: Ordered collections of items accessed by their index values. Lists can be mutable or immutable.
Example:var myList = [1, 2, 3];
-
Map: A collection of unique key-value pairs, similar to dictionaries in Python.
Example:var myMap = {'key1': 'value1', 'key2': 'value2'};
-
Set: Unordered collections of unique items, useful for ensuring no duplicates.
Example:var mySet = {1, 2, 3};
How and Why
Explanation:
Collections simplify programming by allowing developers to group, manage, and manipulate related data efficiently:
- Lists: Useful when the order of items matters.
- Sets: Ensure unique values, such as storing user IDs.
- Maps: Ideal for associating keys with values, like user profiles with IDs.
Why Use Collections:
- Enhance code readability and management.
- Allow dynamic resizing (add/remove items).
- Facilitate operations like sorting, searching, and filtering.
Comparison
-
Lists in Dart vs Arrays in JavaScript:
- Dart lists are type-safe, whereas JavaScript arrays allow mixed types.
-
Sets in Dart vs Sets in Python:
- Both enforce unique elements, but Python allows mixed types, while Dart enforces strict typing.
-
Maps in Dart vs Dictionaries in Python:
- Both store key-value pairs, but Dart maps enforce type safety, reducing runtime errors.
Advantages and Limitations
Advantages:
- Null Safety: Prevents null pointer errors by enforcing nullable or non-nullable values.
- Type Safety: Reduces runtime failures by specifying collection types.
- Built-in Methods: Simplify operations like sorting, filtering, and mapping.
Limitations:
- Strict Typing: Reduces flexibility for mixed data types.
- Complex Annotations: Increases complexity for beginners.
- Null Safety Complexity: Adds learning curve for new developers due to the differences between nullable and non-nullable types.
Q2: Example Implementation
Example 1: Managing a Shopping Cart
Below is an example of a shopping cart where items can be added, removed, and displayed.
Error handling is included to manage cases like removing non-existent items.
void main() {
List<String> shoppingCart = [];
print('Initial Cart: \$shoppingCart');
// Adding items to the cart
shoppingCart.add('Apples');
shoppingCart.add('Bananas');
shoppingCart.add('Oranges');
print('Cart After Adding Items: \$shoppingCart');
// Removing an item
shoppingCart.remove('Bananas');
print('Cart After Removing Bananas: \$shoppingCart');
// Checking if an item is present
bool hasApples = shoppingCart.contains('Apples');
print('Is Apples in the Cart? \$hasApples');
// Clearing the cart
shoppingCart.clear();
print('Cart After Clearing: \$shoppingCart');
}
Output:
Initial Cart: []
Cart After Adding Items: [Apples, Bananas, Oranges]
Cart After Removing Bananas: [Apples, Oranges]
Is Apples in the Cart? true
Cart After Clearing: []
Example 2: Tracking Student Scores
Below is an example of using Dart collections to track student scores, calculate averages, and find the highest and lowest scores.
void main() {
List<int> scores = [85, 90, 78, 92, 88];
print('Student Scores: \$scores');
// Adding a new score
scores.add(95);
print('Scores After Adding New Score: \$scores');
// Calculating the average score
int totalScore = scores.reduce((a, b) => a + b);
double averageScore = totalScore / scores.length;
print('Average Score: \$averageScore');
// Finding highest and lowest scores
int highestScore = scores.reduce((a, b) => a > b ? a : b);
int lowestScore = scores.reduce((a, b) => a < b ? a : b);
print('Highest Score: \$highestScore');
print('Lowest Score: \$lowestScore');
}
Output:
Student Scores: [85, 90, 78, 92, 88]
Scores After Adding New Score: [85, 90, 78, 92, 88, 95]
Average Score: 88.0
Highest Score: 95
Lowest Score: 78
Q3: Real-World Scenario
Managing a List of Tasks in a To-Do App
Imagine creating a To-Do task management app using Flutter. The app allows users to create, edit, view, and delete tasks. Dart Lists can be used to manage and retrieve tasks efficiently.
How Lists Can Be Used:
- Managing the Data: The list of tasks will show all user-created tasks. Each task can be a class containing fields such as description, due date, and status.
- Dynamic Updates: The list updates dynamically when users add, delete, or edit tasks.
- User Interface: The ListView widget in Flutter can display the task list in a user-friendly format. Using
ListView.Builder
ensures dynamic updates. - Checkbox for Completion: Each task can include a checkbox widget to toggle completion status.
- Data Persistence: Tasks can be stored in a database for retrieval after closing the app, ensuring a seamless user experience.